import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

const routes = [
  {
    path: '/admin',
    redirect: '/admin/login'
  },
  {
    path: '/admin/login',
    name: 'Login',
    component: () => import('@/components/Login.vue'),
    meta: {
      title: '宝家人特膳登录'
    }
  },
  {
    path: '/home',
    name: 'Home',
    redirect: '/welcome',
    component: () => import('@/components/Home.vue'),
    meta: {
      title: '宝家人特膳'
    },
    children: [
      {
        path: '/welcome',
        component: () => import('@/components/Welcome.vue'),
        meta: {
          title: '宝家人特膳'
        }
      },
      {
        path: '/users',
        component: () => import('@/components/users/Users.vue'),
        meta: {
          title: '用户列表'
        }
      },
      {
        path: '/rights',
        component: () => import('@/components/power/Rights.vue'),
        meta: {
          title: '权限列表'
        }
      },
      {
        path: '/roles',
        component: () => import('@/components/power/Roles.vue'),
        meta: {
          title: '角色列表'
        }
      },
      {
        path: '/categories',
        component: () => import('@/components/goods/Cate.vue'),
        meta: {
          title: '商品分类'
        }
      },
      {
        path: '/params',
        component: () => import('@/components/goods/Params.vue'),
        meta: {
          title: '分类参数'
        }
      },
      {
        path: '/goods',
        component: () => import('@/components/goods/List.vue'),
        meta: {
          title: '商品列表'
        }
      },
      {
        path: '/goods/add',
        component: () => import('@/components/goods/Add.vue'),
        meta: {
          title: '添加商品'
        }
      },
      {
        path: '/goods/edit',
        component: () => import('@/components/goods/Edit.vue'),
        meta: {
          title: '修改商品'
        }
      }
    ]
  }
]

const router = new VueRouter({
  routes
})
// 挂载路由导航守卫
router.beforeEach((to, from, next) => {
  // to将要访问的路径
  // from 代表从哪个路径跳转而来
  // next 是一个函数, 表示放行
  if (to.path === '/admin' || to.path === '/admin/login') {
    return next()
  }

  const tokenStr = window.sessionStorage.getItem('token')

  if (!tokenStr) {
    return next('/admin/login')
  }
  next()
})
export default router
